<template>
	<div style="padding: 10px;width: 100%;">
		<WMModel v-model:show="show" v-model:params="data.params" :form="data.formAttr" :type="false"
			:rules="data.rules" ref="valid" width="400px">
			<template #footer>
				<el-button type="warning" @click="show=false">取消</el-button>
				<el-button type="success" @click="isadd?save():saveUpdate()">完成</el-button>
			</template>
		</WMModel>
		<el-tabs tab-position="left" style="" class="demo-tabs" @tab-click="changeTag" v-model="activeName">
			<el-tab-pane v-for="(item,i) in cateList" :label="item.name" v-model:name="item.id">
				<div style="display: flex;">
					<el-upload ref="upload" :action="action" :show-file-list="false" :headers="headers"
						:on-success="handleAvatarSuccess" :http-request="uploadFile" multiple :auto-upload="true"
						accept="image/*">
						<el-button type="primary">上传图片</el-button>
					</el-upload>
					<el-button style="margin-left: 10px;" type="primary" @click="add()">添加分类</el-button>
					<el-button type="primary" :disabled="activeName==0 " @click="updateOne()">编辑分类</el-button>
					<el-button type="danger" :disabled="activeName==0 || imageList.length>0"
						@click="deleteOne(activeName)">删除分类</el-button>
					<el-button type="danger" :disabled="isSelect" @click="deleteImage()">删除图片</el-button>
					<el-button type="danger" :disabled="isSelect" @click="selectImageClick()">选中</el-button>
				</div>
				<div style="display: flex;flex-wrap: wrap;">
					<div v-for="(image,index) in imageList" :class="selectId.indexOf(image.id)==-1?'select':'select-on'"
						@click="selectOne(image)">
						<el-image style="width: 100px;height: 100px;margin: 5px;" :src="getImage(image.url)" />
					</div>
				</div>
			</el-tab-pane>
		</el-tabs>
		<el-pagination background v-model:currentPage="page.page" v-model:page-size="page.limit"
			layout="prev, pager, next, jumper" @current-change="prev" :total="page.total">
		</el-pagination>

	</div>
</template>
<script>
	import {
		ElMessage
	} from 'element-plus'
	import {
		reactive,
		toRef,
		ref,
		computed,
		onMounted,
		defineAsyncComponent
	} from 'vue';
	import {
		getEnvs
	} from "/@/utils/envs.js"
	import {
		GLOBAL_DATA
	} from '/@/api/constant'
	import {
		saveImage,
		getImageResourceList,
		deleteImageResource
	} from '/@/api/imageResource.js'
	import {
		getImageCateList,
		addImageCate,
		updateImageCate,
		deleteImageCate
	} from '/@/api/imageCate.js'

	export default {
		components: {
			WMModel: defineAsyncComponent(() => {
				return import('/@/components/from/WMModel.vue')
			})
		},
		props: {
			multiply: {
				type: Boolean,
				default: true
			}
		},

		setup(props, ctx) {
			const page = ref({
				page: 1,
				limit: 18,
				total: 100
			})
			const show = ref(false)
			const data = reactive({
				params: {},
				formAttr: [{
						name: "名称",
						field: "name",
						model: "input"
					},

					{
						name: "排序",
						field: "sort",
						model: "inputNumber"
					},
				],
				rules: {
					name: [{
						required: true,
						message: '请填写',
						trigger: 'blur'
					}, ],
				}
			})
			const imageList = ref([])
			const selectId = ref([])
			const selectImage = ref([])
			const getUrl = () => {
				const {
					envStr
				} = getEnvs()
				return GLOBAL_DATA[envStr]['image-url'];
			}
			const getImage = computed(() => {
				return (image) => {
					if (image) {
						return image.indexOf('http') != -1 ? image : getUrl() + image
					}

					return ''
				}
			})

			const handleAvatarSuccess = (res) => {
				console.log('dta>>>>>>img>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>', res);
				if (res.code == 200) {

					ElMessage({
						message: '上传成功',
						type: 'success',
						duration: 3 * 1000
					})
					getList()
				} else {
					ElMessage({
						message: res.message || 'Error',
						type: 'error',
						duration: 3 * 1000
					})
				}

			}



			const headers = ref({})
			const action = "http://localhost:9106/api/admin/upload/file"
			const uploadFile = (object) => {
				console.log('>>>>ddd>>>>>>>>>>>>>>>>>>>>>>>>>', object.file)
				//参数file文件就是传入的文件流，添加进formDate中
				///this.formDate.append('file', file.file);
				let formData = new FormData()
				formData.append("cateId", activeName.value)
				formData.append('file', object.file)

				saveImage(formData).then(res => {
					object.onSuccess(res)
				})
			}

			const cateList = ref([{
				id: 0,
				name: '全部'
			}])
			const activeName = ref(0)

			const getCateList = () => {
				getImageCateList().then(res => {
					cateList.value = cateList.value.concat(res.data)
				})
			}
			onMounted(() => {
				getCateList()
				getList()
			})

			const changeTag = (tab, event) => {
				console.log(tab, event, '>>>>')
				imageList.value = []
				page.value.page = 1
				getList()
			}

			const prev = (p) => {
				console.log("page>>", p)
				page.value.page = p
				getList()
			}
			const getList = () => {
				getImageResourceList({
					page: page.value.page,
					limit: page.value.limit,
					cateId: activeName.value
				}).then(res => {
					page.value.total = res.data.total
					imageList.value = res.data.list
				})
			}

			const selectOne = (item) => {
				let id = item.id
				console.log('>>', props)
				if (props.multiply) {
					let index = selectId.value.indexOf(id)
					if (index == -1) {
						selectId.value.push(id)
						selectImage.value.push(item)
					} else {
						selectId.value.splice(index, 1)
						selectImage.value.splice(index, 1)
					}
				} else {
					let index = selectId.value.indexOf(id)
					if (index == -1) {
						selectId.value = [id]
						selectImage.value = [item]
					} else {
						selectId.value = []
						selectImage.value = []
					}
				}

			}
			const isSelect = computed(() => {
				return selectId.value.length == 0
			})

			const valid = ref(null)
			const isadd = ref(true)
			const add = () => {
				data.params = {
					statue: 1
				}
				isadd.value = true
				show.value = true

			}
			const deleteOne = (id) => {
				deleteImageCate({
					id: id
				}).then(res => {
					cateList.value = [{
						id: 0,
						name: '全部'
					}]
					activeName.value = '0'
					getCateList()
					data.paage.page = 1
					getList()
				})
			}
			const save = () => {
				valid.value.valid((res) => {
					if (res) {
						addImageCate(data.params).then(res => {
							cateList.value = [{
								id: 0,
								name: '全部'
							}]
							getCateList()
							show.value = false
						})
					}
				})
			}
			const updateOne = () => {
				let row = cateList.value.find(item => item.id == activeName.value)
				data.params = JSON.parse(JSON.stringify(row))
				isadd.value = false
				show.value = true
			}
			const saveUpdate = () => {
				valid.value.valid((res) => {
					if (res) {
						updateImageCate(data.params).then(res => {
							cateList.value = [{
								id: 0,
								name: '全部'
							}]
							getCateList()
							show.value = false
						})
					}
				})
			}

			const deleteImage = () => {

				deleteImageResource({
					id: selectId.value
				}).then(res => {
					selectId.value = []
					selectImage.value = []
					getList()
				})
			}

			const selectImageClick = () => {
				let str = []
				selectImage.value.forEach(item => {
					str.push(item.url)
				})
				if (props.multiply) {
					ctx.emit("onSuccess", str)
				} else {
					ctx.emit("onSuccess", str[0])
				}
			}
			return {
				imageList,
				getImage,
				handleAvatarSuccess,
				headers,
				action,
				uploadFile,
				cateList,
				activeName,
				changeTag,
				page,
				prev,
				selectId,
				selectOne,
				isSelect,
				deleteOne,
				show,
				add,
				save,
				updateOne,
				valid,
				saveUpdate,
				isadd,
				data,
				deleteImage,
				selectImageClick
			}
		}
	}
</script>

<style>
	.select-on {
		background-color: #ffff00;

	}

	.select {}
</style>